/*
 * @Description: 上传
 * @Version: 文件上传
 * @Author: 学渣小宝
 * @Date: 2021-03-29 20:51:49
 * @LastEditors: 学渣小宝
 * @LastEditTime: 2021-03-29 22:42:49
 */
'use strict';

const Controller = require('egg').Controller;
const fs = require('fs');
const path = require('path');
const awaitWriteStream = require('await-stream-ready').write;
class uploadController extends Controller {
  async uploadFile() {
    // 获取文件流
    const stream = await this.ctx.getFileStream();

    // 定义文件名
    const filename = stream.filename;

    // 文件
    const target = path.join('app/public/uploads', filename);
    const writeStream = fs.createWriteStream(target);
    console.log(writeStream);
    try {
      // 文件写入
      await awaitWriteStream(stream.pipe(writeStream));
      this.ctx.status = 200;
    } catch (e) {
      console.log(e);
    }
  }
}

module.exports = uploadController;
